#include "Acceptor.h"
#include "TcpConnection.h"
#include "EventLoop.h"
#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <thread>
#include <chrono>
#include <iomanip>
#include "ThreadPool.h"
#include "EchoServer.h"
#include "LoadBalanceStrategy.h"
using std::cout;
using std::endl;

using TcpConnectionPtr = shared_ptr<TcpConnection>;
using TcpConnectionCallback = function<void(const TcpConnectionPtr &)>;

// 全局变量用于信号处理
EchoServer* g_server = nullptr;
int g_currentStrategy = 1; // 默认最少连接策略
std::thread g_monitorThread;
bool g_running = true;

void printStrategyInfo() {
    const char* strategyNames[] = {"轮询", "最少连接", "一致性哈希", "自适应"};
    cout << "\n========== 当前负载均衡策略: " << strategyNames[g_currentStrategy] 
         << " ==========" << endl;
    cout << "策略编号: 0=轮询, 1=最少连接, 2=一致性哈希, 3=自适应" << endl;
    cout << "发送信号切换策略: kill -USR1 " << getpid() << endl;
    cout << "发送信号退出: kill -USR2 " << getpid() << endl;
}

// 信号处理函数 - 手动切换策略
void signalHandler(int sig) {
    if (sig == SIGUSR1 && g_server) {
        // 循环切换策略
        g_currentStrategy = (g_currentStrategy + 1) % 4;
        g_server->setLoadBalanceStrategy(static_cast<LoadBalanceStrategy>(g_currentStrategy));
        
        const char* strategyNames[] = {"轮询", "最少连接", "一致性哈希", "自适应"};
        cout << "\n[信号切换] 手动切换到策略: " << strategyNames[g_currentStrategy] << endl;
        printStrategyInfo();
    } 
    else if (sig == SIGUSR2) {
        cout << "\n[信号退出] 收到退出信号，正在关闭服务器..." << endl;
        g_running = false;
        if (g_server) {
            g_server->stop();
        }
    }
}

// 运行时动态监控和调整策略
void loadMonitorThread() {
    int adjustCount = 0;
    
    while (g_running) {
        std::this_thread::sleep_for(std::chrono::seconds(10)); // 每10秒检查一次
        
        if (!g_server || !g_running) break;
        
        std::pair<size_t, size_t> connRange = g_server->getConnectionRange();
        size_t minConn = connRange.first;
        size_t maxConn = connRange.second;
        
        if (minConn == 0 && maxConn == 0) {
            cout << "[负载监控] 暂无连接，等待客户端连接..." << endl;
            continue;
        }
        
        // 计算总连接数和负载监控
        size_t totalConns = minConn + maxConn; // 粗略估算
        
        // 高负载保护
        if (totalConns > 800) {
            cout << "\n⚠️  [高负载警告] 总连接数≈" << totalConns << " 超过800，服务器可能过载！" << endl;
        }
        if (totalConns > 1000) {
            cout << "\n🚨 [严重警告] 总连接数≈" << totalConns << " 超过1000，建议限制新连接！" << endl;
        }
        
        double loadImbalance = (minConn == 0) ? 
            (maxConn > 0 ? 2.0 : 0.0) : 
            (double)(maxConn - minConn) / minConn;
            
        cout << "\n[负载监控] 连接分布 - 最少: " << minConn 
             << ", 最多: " << maxConn 
             << ", 不均衡度: " << std::fixed << std::setprecision(2) << loadImbalance << endl;
        
        LoadBalanceStrategy recommendStrategy = static_cast<LoadBalanceStrategy>(g_currentStrategy);
        bool shouldAdjust = false;
        
        // 自动调整策略逻辑
        if (loadImbalance > 0.8) {
            // 负载严重不均，推荐最少连接策略
            if (g_currentStrategy != 1) {
                recommendStrategy = LoadBalanceStrategy::LEAST_CONNECTIONS;
                shouldAdjust = true;
                cout << "[负载监控] 检测到负载严重不均(不均衡度>" << loadImbalance 
                     << ")，推荐切换到最少连接策略" << endl;
            }
        } 
        else if (loadImbalance < 0.3 && maxConn >= 3) {
            // 负载相对均衡且有一定连接数，可以使用一致性哈希保持会话亲和性
            if (g_currentStrategy != 2 && g_currentStrategy != 3) {
                recommendStrategy = LoadBalanceStrategy::ADAPTIVE;
                shouldAdjust = true;
                cout << "[负载监控] 负载相对均衡(不均衡度<" << loadImbalance 
                     << ")，推荐切换到自适应策略" << endl;
            }
        }
        
        // 执行自动调整（可配置是否启用）
        static bool enableAutoAdjust = true; // 可以通过配置控制
        if (shouldAdjust && enableAutoAdjust) {
            adjustCount++;
            g_currentStrategy = static_cast<int>(recommendStrategy);
            g_server->setLoadBalanceStrategy(recommendStrategy);
            
            const char* strategyNames[] = {"轮询", "最少连接", "一致性哈希", "自适应"};
            cout << "[自动调整] 第" << adjustCount << "次自动调整到策略: " 
                 << strategyNames[g_currentStrategy] << endl;
        }
    }
    
    cout << "[负载监控] 监控线程退出" << endl;
}

void test()
{
    cout << "=== 多Reactor负载均衡测试服务器 ===" << endl;
    cout << "服务器地址: 127.0.0.1:8888" << endl;
    cout << "SubReactor数量: 4" << endl;
    
    // 设置信号处理
    signal(SIGUSR1, signalHandler); // 切换策略
    signal(SIGUSR2, signalHandler); // 退出服务器
    // signal(SIGINT, signalHandler);  // Ctrl+C 退出
    
    EchoServer server("127.0.0.1", 8888, 4); // 增加到4个SubReactor
    g_server = &server;
    
    // 启动时设置初始策略和连接数限制
    server.setLoadBalanceStrategy(static_cast<LoadBalanceStrategy>(g_currentStrategy));
    //LoadBalanceStrategy::LEAST_CONNECTIONS LoadBalanceStrategy::CONSISTENT_HASH有bug
    // server.setLoadBalanceStrategy(LoadBalanceStrategy::ROUND_ROBIN);
    server.setMaxConnections(100000); // 设置最大连接数
    printStrategyInfo();
    
    cout << "最大连接数限制: " << server.getMaxConnections() << endl;
    
    // 启动负载监控线程
    g_monitorThread = std::thread(loadMonitorThread);
    
    cout << "\n测试连接命令:" << endl;
    cout << "telnet 127.0.0.1 8888" << endl;
    cout << "或者: nc 127.0.0.1 8888" << endl;
    cout << "\n服务器启动中..." << endl;
    
    server.start(); // 阻塞运行
    
    // 等待监控线程结束
    if (g_monitorThread.joinable()) {
        g_monitorThread.join();
    }
    
    cout << "服务器已关闭" << endl;
}

void printUsage(const char* programName) {
    cout << "用法: " << programName << " [选项]" << endl;
    cout << "选项:" << endl;
    cout << "  --port <端口>        监听端口 (默认: 8888)" << endl;
    cout << "  --max-conn <数量>    最大连接数 (默认: 100000)" << endl;
    cout << "  --sub-reactors <数量> SubReactor数量 (默认: 8)" << endl;
    cout << "  --strategy <策略>    负载均衡策略 (0=轮询, 1=最少连接, 2=一致性哈希, 3=自适应)" << endl;
    cout << "  --help               显示此帮助信息" << endl;
    cout << endl;
    cout << "示例:" << endl;
    cout << "  " << programName << " --port 8888 --max-conn 50000" << endl;
    cout << "  " << programName << " --port 8889 --strategy 0" << endl;
}

struct ServerConfig {
    unsigned short port = 8888;
    size_t maxConnections = 100000;
    int subReactors = 8;
    int strategy = 1; // 默认最少连接
    std::string ip = "127.0.0.1";
};

ServerConfig parseArgs(int argc, char* argv[]) {
    ServerConfig config;
    
    for (int i = 1; i < argc; i++) {
        std::string arg = argv[i];
        
        if (arg == "--help" || arg == "-h") {
            printUsage(argv[0]);
            exit(0);
        }
        else if (arg == "--port" && i + 1 < argc) {
            config.port = static_cast<unsigned short>(std::stoi(argv[++i]));
        }
        else if (arg == "--max-conn" && i + 1 < argc) {
            config.maxConnections = static_cast<size_t>(std::stoul(argv[++i]));
        }
        else if (arg == "--sub-reactors" && i + 1 < argc) {
            config.subReactors = std::stoi(argv[++i]);
        }
        else if (arg == "--strategy" && i + 1 < argc) {
            config.strategy = std::stoi(argv[++i]);
        }
        else if (arg == "--ip" && i + 1 < argc) {
            config.ip = argv[++i];
        }
        else {
            cout << "未知参数: " << arg << endl;
            printUsage(argv[0]);
            exit(1);
        }
    }
    
    return config;
}

int main(int argc,char *argv[])
{
    test();
    // ServerConfig config = parseArgs(argc, argv);
    
    // cout << "=== 多Reactor负载均衡测试服务器 ===" << endl;
    // cout << "服务器地址: " << config.ip << ":" << config.port << endl;
    // cout << "SubReactor数量: " << config.subReactors << endl;
    // cout << "最大连接数: " << config.maxConnections << endl;
    
    // // 设置信号处理
    // signal(SIGUSR1, signalHandler); // 切换策略
    // signal(SIGUSR2, signalHandler); // 退出服务器
    
    // EchoServer server(config.ip, config.port, config.subReactors);
    // g_server = &server;
    
    // // 设置策略和连接数限制
    // server.setLoadBalanceStrategy(static_cast<LoadBalanceStrategy>(config.strategy));
    // server.setMaxConnections(config.maxConnections);
    
    // const char* strategyNames[] = {"轮询", "最少连接", "一致性哈希", "自适应"};
    // cout << "负载均衡策略: " << strategyNames[config.strategy] << endl;
    // cout << "进程PID: " << getpid() << endl;
    
    // cout << "\n服务器启动中..." << endl;
    // server.start(); // 阻塞运行
    
    // cout << "服务器已关闭" << endl;
    return 0;
}


